#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
 
class ExpiredQualityBatch(models.Model):
    _name = 'expired.quality.batch' 
    _description = '过期品检批次'
 
    name = fields.Char('批次号', readonly=True, required=True, copy=False, default=lambda self: self._generate_product_timeout_number()) 
    def _generate_product_timeout_number(self):
        seq = self.env['ir.sequence'].next_by_code('sb.product.timeout.number') or 'New'
        return seq
    date = fields.Date('日期', default=fields.Date.today) 
    move_ids = fields.One2many('stock.move',  'batch_id', string='库存移动')
    quality_check_ids = fields.One2many('quality.check',  'batch_id', string='质检单')
    state = fields.Selection([
        ('draft', '草稿'),
        ('in_progress', '进行中'),
        ('checking', '检查中'),
        ('done', '完成'),
        ('cancel', '取消')], default='draft', string='状态')

    _sql_constraints = [
        ('name_unique', 'UNIQUE(name)', '批次号必须唯一！'),
    ]

    def action_to_inprogress(self):
        self.ensure_one()
        if not self.filtered(lambda x:x.state == 'draft'):
            raise ValidationError(_("提交单据时状态错误，当前状态：{state}").format(state=self.state))
        self.state = 'in_progress'

    def action_to_checking(self):
        self.ensure_one()
        if not self.filtered(lambda x:x.state == 'in_progress'):
            raise ValidationError(_("提交单据时状态错误，当前状态：{state}").format(state=self.state))
        self.state = 'checking'

    def action_to_done(self):
        self.ensure_one()
        if not self.filtered(lambda x:x.state == 'checking'):
            raise ValidationError(_("完成单据时状态错误，当前状态：{state}").format(state=self.state))
        self.state = 'done'

    def action_to_cancel(self):
        self.ensure_one()
        if not self.filtered(lambda x:x.state == 'in_progress'):
            raise ValidationError(_("取消单据时状态错误，当前状态：{state}").format(state=self.state))
        self.state = 'cancel'

    def action_to_draft(self):
        self.ensure_one()
        if not self.filtered(lambda x:x.state == 'cancel'):
            raise ValidationError(_("设为草稿时状态错误，当前状态：{state}").format(state=self.state))
        self.state = 'draft'

    #def action_create_scrap_picking(self, scrap_qty):
    #    self.ensure_one()
    ##  def check_expired_products_to_stock(self, batch, picking):
    #    #  stock_code = self.env.ref('stock.stock_location_stock')
    #    scrap_code = self.env.ref('sb_product_expiry_ext.stock_location_scrapped')
    #    check_code = self.env.ref('sb_product_expiry_ext.stock_location_quality_control')
    #    #  expired_quants = self.search([
    #        #  ('lot_id', '!=', False),
    #        #  ('location_id', '=', scrap_code.id),
    #        #  ('product_id.use_expiration_date',  '=', True),
    #        #  ('lot_id.expiration_date',  '<', fields.Date.today())
    #    #  ])
    #    picking_type = self.env.ref('sb_product_expiry_ext.picking_type_expired_quality')
    #    #  batch = self.env['expired.quality.batch'].create({'date':  fields.Date.today()})
    #    moves = self.env['stock.move'] 
    #    picking_pool = self.env['stock.picking']
    #    old_check_ids = picking_pool.search([('picking_type_id','=',picking_type.id),('location_id','=',check_code.id),('location_dest_id','=',scrap_code.id)])
    #    if old_check_ids.move_ids.filtered(lambda x:x == self):
    #    #  if old_check_ids:
    #        raise ValidationError(_("发现已经存在报废单，不用重复创建!"))
    #    picking_id = picking_pool.create({
    #        'picking_type_id': picking_type.id,
    #        'location_id': check_code.id,
    #        'location_dest_id': scrap_code.id, 
    #    })
    #    for move in self.move_ids:
    #        new_move = self.env['stock.move'].create({ 
    #            'picking_id': picking_id.id,
    #            'name': f'过期品报废处理-{move.product_id.name}', 
    #            'product_id': move.product_id.id, 
    #            'product_uom_qty': scrap_qty, 
    #            'location_id': check_code.id, 
    #            'location_dest_id': scrap_code.id, 
    #            'picking_type_id': picking_type.id,
    #            'batch_id': self.id,
    #            #  'lot_ids': [(4, move.lot_id.id)],
    #            'lot_ids': [(4,x.id) for x in move.lot_ids],
    #        })
    #        vals = []
    #        for m_l in move.move_line_ids:
    #            vals+= [(0, 0, {
    #                'product_id': m_l.product_id.id,
    #                'lot_id': m_l.lot_id.id,
    #                'qty_done': scrap_qty,
    #                'location_id': check_code.id,
    #                'location_dest_id': scrap_code.id,
    #            })]
    #        new_move.write({'move_line_ids':vals})
    #        moves += new_move 
    #    moves._action_confirm()
    #    return picking_id

    def action_create_back_to_stock(self):
        self.ensure_one()
    #  def check_expired_products_to_stock(self, batch, picking):
        stock_code = self.env.ref('stock.stock_location_stock')
        scrap_code = self.env.ref('sb_product_expiry_ext.stock_location_quality_control')
        #  expired_quants = self.search([
            #  ('lot_id', '!=', False),
            #  ('location_id', '=', scrap_code.id),
            #  ('product_id.use_expiration_date',  '=', True),
            #  ('lot_id.expiration_date',  '<', fields.Date.today())
        #  ])
        picking_type = self.env.ref('sb_product_expiry_ext.picking_type_expired_quality')
        #  batch = self.env['expired.quality.batch'].create({'date':  fields.Date.today()})
        moves = self.env['stock.move'] 
        picking_pool = self.env['stock.picking']
        old_check_ids = picking_pool.search([('picking_type_id','=',picking_type.id),('location_id','=',scrap_code.id),('location_dest_id','=',stock_code.id)])
        if old_check_ids.move_ids.filtered(lambda x:x == self):
        #  if old_check_ids:
            raise ValidationError(_("发现已经存在返库单，不用重复创建!"))
        picking_id = picking_pool.create({
            'picking_type_id': picking_type.id,
            'location_id': scrap_code.id,
            'location_dest_id': stock_code.id, 
        })
        for move in self.move_ids:
            new_move = self.env['stock.move'].create({ 
                'picking_id': picking_id.id,
                'name': f'过期品返库处理-{move.product_id.name}', 
                'product_id': move.product_id.id, 
                'product_uom_qty': move.quantity, 
                'location_id': scrap_code.id, 
                'location_dest_id': move.location_id.id, 
                'picking_type_id': picking_type.id,
                'batch_id': self.id,
                #  'lot_ids': [(4, move.lot_id.id)],
                'lot_ids': [(4,x.id) for x in move.lot_ids],
            })
            vals = []
            for m_l in move.move_line_ids:
                vals+= [(0, 0, {
                    'product_id': m_l.product_id.id,
                    'lot_id': m_l.lot_id.id,
                    'qty_done': m_l.quantity,
                    'location_id': scrap_code.id,
                    'location_dest_id': m_l.location_id.id,
                })]
            new_move.write({'move_line_ids':vals})
            moves += new_move 
        moves._action_confirm()
        #  batch.action_create_quality_checks()
        self.action_to_inprogress()
        return picking_id

    def action_create_quality_checks(self):
        qua_check_pool = self.env['quality.check']
        stock_code = self.env.ref('stock.stock_location_stock')
        check_code = self.env.ref('sb_product_expiry_ext.stock_location_quality_control')
        for batch in self:
            old_row = qua_check_pool.search([('batch_id','=',batch.id)])
            if old_row:
                raise ValidationError(f"发现已经存在返库单，不用重复创建!{old_row.mapped('name')}")
            quality_checks = self.env['quality.check'] 
            #  for move in batch.move_ids.filtered(
                    #  lambda x:x.location_id == check_code and x.location_dest_id == stock_code
            #  ).mapped(lambda x:x.move_line_ids):
            for move in batch.move_ids.filtered(
                    lambda x:x.location_id == check_code
            ).mapped(lambda x:x.move_line_ids): 
                check = qua_check_pool.create({ 
                    'move_id':move.move_id.id,
                    'move_line_id':move.id,
                    'picking_id': move.move_id.picking_id.id,
                    'product_id': move.product_id.id, 
                    'batch_id': batch.id, 
                    'point_id': self.env.ref('sb_product_expiry_ext.quality_check_expired').id,
                    'lot_line_id': move.lot_id.id,
                    'lot_id': move.lot_id.id,
                    'product_uom_qty': move.lot_id.product_qty,
                    'uom_id': move.lot_id.product_uom_id.id,
                    'team_id': self.env.ref('sb_product_expiry_ext.quality_alert_qc_team0').id
                })
                quality_checks += check 
            batch.quality_check_ids  = quality_checks 
            if batch.filtered(lambda x:x.state != 'checking'):
                batch.action_to_checking()
